<?php

//品牌

class Brand extends Admin_Controller {

	public function __construct()
	{
		parent::__construct();
		$this->load->model('brand_model');
	}

	public function index()
	{
		$p = intval(get('p'));
		$p = $p ? $p : 1;
		
		$per_page = 20;

		$count = $this->brand_model->get_count();
		$brand_list = $this->brand_model->get_page($p, $per_page);
		
		$this->load->library('page');
		$config = array(
			'base_url' => admin_url('brand/index'),
			'total_rows' => $count,
			'current_page' => $p,
			'per_page' => $per_page
		);
		$this->page->config($config)->init();
		
		$this->template->assign('list', $brand_list);
		$this->template->assign('page', $this->page);
		$this->template->display('brand/list');
	}

	//搜索
	public function search()
	{
		$p = intval(get('p'));
		$p = $p ? $p : 1;

		$name = trim(get('name'));
		
		$per_page = 20;

		$result = $this->db->select('count(*) as count')->from('brand')->like('name', $name)->get()->row_array();
		$count = $result['count'];

		$brand_list = $this->db->select('id, name, url, logo')->from('brand')->like('name', $name)->limit($per_page, ($p-1)*$per_page)->get()->result_array();
		
		$this->load->library('page');
		$config = array(
			'base_url' => admin_url('brand/search'),
			'total_rows' => $count,
			'current_page' => $p,
			'per_page' => $per_page
		);
		$this->page->config($config)->init();
		
		$this->template->assign('list', $brand_list);
		$this->template->assign('page', $this->page);
		$this->template->display('brand/list');
	}

	//添加品牌页面
	protected function _insert_get()
	{
		$this->template->display('brand/insert');
	}
	
	//提交添加品牌
	protected function _insert_post()
	{
		$name = trim(post('name')); //品牌名称
		$url = trim(post('url')); //品牌网址
		$title = trim(post('title')); //标题
		$keywords = trim(post('keywords')); //关键词
		$description = trim(post('description')); //描述
		$content = trim(post('content')); //内容
		$logo = ''; //图标
		
		if ($name == '')
		{
			msg('名称必须填写！', -1);
		}
		
		if (isset($_FILES['logo']) && $_FILES['logo']['name'])
		{
			$this->load->library('upload');
			$config = array(
				'upload_path' => FCPATH.'assets/uploads/images/barad/',
				'allowed_types' => array('jpg', 'jpeg', 'png', 'gif')
			);
			$this->upload->config($config)->init();
			if ( ! $this->upload->upload_file($_FILES['logo']))
			{
				msg($this->upload->get_error(), -1);
			}
			$data = $this->upload->get_data();
			$logo = $data['relative_filename'];
		}
		
		if ($this->brand_model->exists(array('name' => $name)))
		{
			msg('品牌名称已经存在！', -1);
		}
		
		$data = array(
			'name' => $name,
			'url' => $url,
			'logo' => $logo,
			'title' => $title,
			'keywords' => $keywords,
			'description' => $description,
			'content' => $content
		);
		
		if ( ! ($id = $this->brand_model->insert($data)))
		{
			log_message('error', '添加品牌失败！原因：写入brand表失败！');
			msg('添加失败！');
		}
		
		$msg = '添加成功！<br /><br /><a href="'.admin_url('brand/update', array('id' => $id)).'" class="button">返回修改</a>&nbsp;&nbsp;&nbsp;<a href="'.admin_url('brand/insert').'" class="button">继续添加</a>&nbsp;&nbsp;&nbsp;<a href="'.$this->session->get('back').'" class="button">返回列表</a>';
		msg($msg);
	}
	
	//修改页面
	protected function _update_get()
	{
		$id = intval(get('id'));
		if ($id < 1)
		{
			msg('非法访问！');
		}
		
		$brand_data = $this->brand_model->get($id);
		if ( ! $brand_data)
		{
			msg('品牌不存在！', admin_url('brand/index'));
		}
		
		$this->template->assign('data', $brand_data);
		$this->template->display('brand/update');
	}
	
	//提交修改信息
	protected function _update_post()
	{
		$id = intval(post('id')); //品牌id
		$name = trim(post('name')); //品牌名称
		$url = trim(post('url')); //品牌网站
		$title = trim(post('title')); //标题
		$keywords = trim(post('keywords')); //关键词
		$description = trim(post('description')); //描述
		$content = trim(post('content')); //内容
		$logo = ''; //图标
		$delete_logo = intval(post('delete_logo')) > 0 ? TRUE : FALSE;
		
		if ($id < 1)
		{
			msg('非法访问！');
		}
		
		if ( ! $delete_logo && isset($_FILES['logo']) && $_FILES['logo']['name'])
		{
			$this->load->library('upload');
			$config = array(
				'upload_path' => FCPATH.'assets/uploads/images/brand/',
				'allowed_types' => array('jpg', 'jpeg', 'png', 'gif')
			);
			
			if ( ! $this->upload->config($config)->init())
			{
				msg($this->upload->get_error(), -1);
			}
			
			if ( ! $this->upload->upload_file($_FILES['logo']))
			{
				msg($this->upload->get_error(), -1);
			}
			$data = $this->upload->get_data();
			$logo = $data['relative_filename'];
		}
		
		$brand_data = $this->brand_model->get($id);
		if ( ! $brand_data)
		{
			msg('品牌不存在！', admin_url('brand/index'));
		}
		
		if ($brand_data['name'] != $name)
		{
			if ($this->brand_model->exists(array('name' => $name)))
			{
				msg('品牌名称已经存在！', -1);
			}
		}
		
		$data = array(
			'name' => $name,
			'url' => $url,
			'title' => $title,
			'keywords' => $keywords,
			'description' => $description,
			'content' => $content
		);
		
		if ($delete_logo || $logo)
		{
			$data['logo'] = $logo;
		}
		
		if (FALSE === $this->brand_model->update($data, $id))
		{
			log_message('error', '修改品牌失败！原因：更新brand表失败！');
			msg('修改失败！');
		}
		
		$msg = '修改成功！<br /><br /><a href="'.admin_url('brand/update', array('id' => $id)).'" class="button">继续修改</a>&nbsp;&nbsp;&nbsp;<a href="'.$this->session->get('back').'" class="button">返回列表</a>';
		msg($msg);
	}
	
	//删除品牌
	public function _delete_ajax()
	{
		$id = intval(get('id'));
		
		if ($id < 1)
		{
			ajax(array('error' => 1, 'msg' => '非法请求！'));
		}
		
		$result = $this->brand_model->delete($id);
		
		if ($result !== FALSE)
		{
			ajax(array('error' => 0, 'msg' => '删除成功！'));
		}
		else
		{
			log_message('error', '删除品牌失败！原因：更新brand表失败！');
			ajax(array('error' => 2, 'msg' => '删除失败！'));
		}
	}

	//导出excel
	public function export()
	{
		$type = get('type');
		if ($type == 'excel')
		{
			$this->_export_to_excel();
		}
		elseif ($type == 'txt')
		{
			$this->_export_to_txt();
		}
	}

	//导出excel
	public function _export_to_excel()
	{
		$this->load->library('PHPExcel', NULL, 'phpexcel');
		$this->phpexcel->setActiveSheetIndex(0)
			->setCellValue('A1', 'ID')
			->setCellValue('B1', '名称')
			->setCellValue('C1', '网址')
			->setCellValue('D1', '图标');

		//设置列宽度
		$this->phpexcel->getActiveSheet()->getColumnDimension('A')->setWidth(10);
		$this->phpexcel->getActiveSheet()->getColumnDimension('B')->setWidth(30);
		$this->phpexcel->getActiveSheet()->getColumnDimension('C')->setWidth(20);
		$this->phpexcel->getActiveSheet()->getColumnDimension('D')->setWidth(20);

		//设置字体粗体
		$this->phpexcel->getActiveSheet()->getStyle('A1')->getFont()->setBold(TRUE);
		$this->phpexcel->getActiveSheet()->getStyle('B1')->getFont()->setBold(TRUE);
		$this->phpexcel->getActiveSheet()->getStyle('C1')->getFont()->setBold(TRUE);
		$this->phpexcel->getActiveSheet()->getStyle('D1')->getFont()->setBold(TRUE);

		$list = $this->brand_model->get_all(NULL, 'id, name, url, logo');
		$i = 2;

		if ($list)
		{
			$objDrawing = new PHPExcel_Worksheet_Drawing();
			foreach ($list as $row)
			{
				$this->phpexcel->setActiveSheetIndex(0)
					->setCellValue('A'.$i, $row['id'])
					->setCellValue('B'.$i, $row['name'])
					->setCellValue('C'.$i, $row['url'])
					->setCellValue('D'.$i, '');

				if ($row['logo'] && file_exists($_SERVER['DOCUMENT_ROOT'].$row['logo']))
				{
					$objDrawing->setPath($_SERVER['DOCUMENT_ROOT'].$row['logo']);
					$objDrawing->setCoordinates('D'.$i);
					$objDrawing->setWorksheet($this->phpexcel->getActiveSheet());
				}

				$i++;
			}
		}

		header('Content-Type: application/vnd.ms-excel');
		header('Content-Disposition: attachment;filename="品牌-'.date('Y-m-d').'.xls"');
		header('Cache-Control: max-age=0');

		$objWriter = PHPExcel_IOFactory::createWriter($this->phpexcel, 'Excel5');
		$objWriter->save('php://output');
	}

	//导出txt
	public function _export_to_txt()
	{
		$list = $this->brand_model->get_all(NULL, 'id, name, url, logo');
		$txt = "ID\t名称\t网址\t图标\n";
		if ($list)
		{
			foreach ($list as $row)
			{
				$txt .= $row['id']."\t".$row['name']."\t".$row['url']."\t".$row['logo']."\n";
			}
		}

		$this->load->helper('download');
		force_download('品牌-'.date('Y-m-d').'.txt', $txt);
	}
	
}